<template>
  <div id="app">
 <MyHeader title="购物车案例"></MyHeader>
 <MyGoods
 v-for="item in list"
 :key="item.id"
 :id="item.id"
 :goods="item"
@changeCount="changeCount"
@changeState="changeState"
@changeCountNum="changeCountNum"
 ></MyGoods>
 <MyFooter
 :list="list"
 @allSelect="allSelect"
 ></MyFooter>
  </div>
</template>

<script>
import MyHeader from './components/MyHeader.vue'
import MyGoods from './components/MyGoods.vue'
import MyFooter from './components/MyFooter.vue'
export default {
  name: 'App',
  components:{
      MyHeader,
      MyGoods,
      MyFooter
  },
  data(){
      return {
          list:[]
      }
  },
//   初始化完成后请求axios数据
 async created(){
    this.$axios({
          url:'/api/cart'
      }
      
      ).then(res=>{
          this.list=res.data.list
      })
  },
  methods: {
      changeCount(isAddOrMinus,id){
        if(isAddOrMinus=="add"){
        let index = this.list.findIndex(item=>item.id==id)
        this.list[index].goods_count++;
        }else{
         let index = this.list.findIndex(item=>item.id==id)
        this.list[index].goods_count--;
          }
      },
      changeState(id){
            let index = this.list.findIndex(item=>item.id==id)
        this.list[index].goods_state=!this.list[index].goods_state
      },
      allSelect(selected){
          this.list.forEach(item=>{
              item.goods_state=selected
          })
      },
      changeCountNum(num,id){
             let index = this.list.findIndex(item=>item.id==id)
             this.list[index].goods_count=num
      }
  },
}
</script>

<style>
#app{
    padding:45px 0 50px 0;
}
</style>
